package com.ruoyi.swla2.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.swla2.domain.DfqFreeze;
import com.ruoyi.swla2.domain.TerminalHistoryData;
import com.ruoyi.swla2.model.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.swla2.domain.DmaFreeze;
import com.ruoyi.swla2.service.IDmaFreezeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * dma冻结数据Controller
 *
 * @author gdqt
 * @date 2023-08-28
 */
@RestController
@RequestMapping("/swla2/freezeDma")
public class DmaFreezeController extends BaseController {
    @Autowired
    private IDmaFreezeService dmaFreezeService;

    @PreAuthorize("@ss.hasPermi('swla2:freezeDfq:list')")
    @GetMapping("/getDmaMinNightFlowData")
    public AjaxResult getDmaMinNightFlowData(@RequestParam Map<String, Object> paramMap) {
        System.out.println(paramMap);
        List<DmaFreeze> dmaFreezeList = dmaFreezeService.selectDmaMinNightFlow(paramMap);
        return AjaxResult.success(dmaFreezeList);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDfq:list')")
    @GetMapping("/getDmaPressureData")
    public AjaxResult getDmaPressureData(@RequestParam Map<String, Object> paramMap) {
        List<DmaPressureDataModel> dmaPressureDataModelList = dmaFreezeService.selectDmaPressureData(paramMap);
        return AjaxResult.success(dmaPressureDataModelList);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDfq:list')")
    @GetMapping("/getDmaLeakageCompositionData")
    public AjaxResult getDmaLeakageCompositionData(@RequestParam Map<String, Object> paramMap) {
        DmaLeakageCompositionModel compositionModel = dmaFreezeService.selectDmaLeakageComposition(paramMap);
        return AjaxResult.success(compositionModel);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDfq:list')")
    @GetMapping("/getDmaProdsaleAnalysisData")
    public AjaxResult getDmaProdsaleAnalysisData(@RequestParam Map<String, Object> paramMap) {
        Map<String, Object> resultMap = new HashMap<>();

        String startDate, endDate;
        Object queryDates = paramMap.get("queryDates");
        if (queryDates == null) {
            startDate = LocalDate.now().minusMonths(6L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
            endDate = LocalDate.now().minusMonths(1L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
        } else {
            String[] dates = queryDates.toString().split(",");
            startDate = dates[0];
            endDate = dates[1];
        }

        FreezeDataQueryModel model = new FreezeDataQueryModel();
        model.setAreaId(paramMap.get("areaId").toString());
        model.setStartDate(startDate);
        model.setEndDate(endDate);
        model.setFrozenType("month");
        List<DmaFreeze> dfqFreezeList = dmaFreezeService.selectDmaFreezeByQueryModel(model);
        dfqFreezeList.sort(Comparator.comparing(DmaFreeze::getFreezetime));

        resultMap.put("timeList", dfqFreezeList.stream().map(DmaFreeze::getFreezetime).collect(Collectors.toList()));
        resultMap.put("supply", dfqFreezeList.stream().map(item -> item.getInputFlow().doubleValue()).collect(Collectors.toList()));
        resultMap.put("sale", dfqFreezeList.stream().map(item -> item.getSaleWater().doubleValue()).collect(Collectors.toList()));
        resultMap.put("free", dfqFreezeList.stream().map(item -> item.getFreeWater().doubleValue()).collect(Collectors.toList()));
        resultMap.put("cxcl", dfqFreezeList.stream().map(item -> Double.valueOf(item.getCxcl())).collect(Collectors.toList()));

        return AjaxResult.success(resultMap);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDfq:list')")
    @GetMapping("/getDmaSupplyAnalysisData")
    public AjaxResult getDmaSupplyAnalysisData(@RequestParam Map<String, Object> paramMap) {
        Map<String, Object> resultMap = new HashMap<>();

        String startDate, endDate;
        Object freezetime = paramMap.get("freezetime");
        if (freezetime == null) {
            startDate = LocalDate.now().minusMonths(5L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
            endDate = LocalDate.now().minusMonths(1L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
        } else {
            endDate = freezetime.toString();
            startDate = LocalDate.parse(endDate + "-01").minusMonths(5L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
        }

        FreezeDataQueryModel model = new FreezeDataQueryModel();
        model.setAreaId(paramMap.get("areaId").toString());
        model.setStartDate(startDate);
        model.setEndDate(endDate);
        model.setFrozenType("month");
        List<DmaFreeze> dfqFreezeList = dmaFreezeService.selectDmaFreezeByQueryModel(model);
        dfqFreezeList.sort(Comparator.comparing(DmaFreeze::getFreezetime));

        resultMap.put("timeList", dfqFreezeList.stream().map(DmaFreeze::getFreezetime).collect(Collectors.toList()));
        resultMap.put("supply", dfqFreezeList.stream().map(item -> item.getInputFlow().doubleValue()).collect(Collectors.toList()));
        resultMap.put("hb", dfqFreezeList.stream().map(DmaFreeze::getHb).collect(Collectors.toList()));

        return AjaxResult.success(resultMap);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDfq:list')")
    @GetMapping("/listByQueryModel")
    public TableDataInfo listByQueryModel(FreezeDataQueryModel model) {
        startPage();
        List<DmaFreeze> list = dmaFreezeService.selectDmaFreezeByQueryModel(model);
        return getDataTable(list);
    }

    /**
     * 查询dma冻结数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDma:list')")
    @GetMapping("/list")
    public TableDataInfo list(DmaFreeze dmaFreeze) {
        startPage();
        List<DmaFreeze> list = dmaFreezeService.selectDmaFreezeList(dmaFreeze);
        return getDataTable(list);
    }

    /**
     * 导出dma冻结数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDma:export')")
    @Log(title = "dma冻结数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FreezeDataQueryModel model) {
        List<DmaFreeze> list = dmaFreezeService.selectDmaFreezeByQueryModel(model);
        list.forEach(dmaFreeze -> {
            dmaFreeze.setAreaName(dmaFreeze.getZone().getAreaName());

            BigDecimal lsl = BigDecimal.ZERO;
            if (dmaFreeze.getInputFlow() != null && dmaFreeze.getSaleWater() != null && dmaFreeze.getInputFlow().doubleValue() != 0.0) {
                if (model.getFrozenType().equals("month")) {
                    if (dmaFreeze.getPhysicalLeakageMonth() != null) {
                        dmaFreeze.setPhysicalLeakageDaily(dmaFreeze.getPhysicalLeakageMonth());
                        lsl = dmaFreeze.getPhysicalLeakageMonth().divide(dmaFreeze.getInputFlow(), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                    }
                } else {
                    if (dmaFreeze.getPhysicalLeakageDaily() != null) {
                        lsl = dmaFreeze.getPhysicalLeakageDaily().divide(dmaFreeze.getInputFlow(), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                    }
                }
            }
            dmaFreeze.setLsl(NumberUtil.round(lsl, 2).toString());
        });
        ExcelUtil<DmaFreeze> util = new ExcelUtil<DmaFreeze>(DmaFreeze.class);
        util.exportExcel(response, list, "DMA冻结数据数据");
    }

    /**
     * 获取dma冻结数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDma:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(dmaFreezeService.selectDmaFreezeById(id));
    }

    /**
     * 新增dma冻结数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDma:add')")
    @Log(title = "dma冻结数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DmaFreeze dmaFreeze) {
        dmaFreeze.setTenantId(this.getTenantId());
        return toAjax(dmaFreezeService.insertDmaFreeze(dmaFreeze));
    }

    /**
     * 修改dma冻结数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDma:edit')")
    @Log(title = "dma冻结数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DmaFreeze dmaFreeze) {
        return toAjax(dmaFreezeService.updateDmaFreeze(dmaFreeze));
    }

    /**
     * 删除dma冻结数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDma:remove')")
    @Log(title = "dma冻结数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(dmaFreezeService.deleteDmaFreezeByIds(ids));
    }


    /**
     * 查询DMA冻结数据列表
     */
    @GetMapping("/report/dma")
    public TableDataInfo listDma(FreezeDataQueryModel model) {
        model.setTenantId(this.getTenantId());
        startPage();
        List<DmaFreeze> list = dmaFreezeService.selectDmaFreezeReportList(model);
        return getDataTable(list);
    }
}
